from twisted.internet.protocol import Protocol, ClientFactory
from twisted.internet import reactor
from protobuf_generated import example_pb2
from twisted.internet import task
import struct
import random
import platform

global msg_count
global greetings

def generate_random_str():
    random_str = ''
    base_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789'
    length = len(base_str) - 1
    for i in range(0, 1024 * 32, 64):
        random_str += base_str[random.randint(0, length)]
    return random_str

class RobotProtocol(Protocol):    
    def __init__(self):
        self.data = ''
        
    def connectionMade(self):
        global greetings
        req = example_pb2.DummyReq()
        req.greetings = greetings[int(random.uniform(0, len(greetings)))]
        self.send(2, req)
        
    def connectionLost(self, reason):
        pass

    def dataReceived(self, data):
        global msg_count
        self.data += data
        while len(self.data) >= 8:
            l, msg_id = struct.unpack('!2I', self.data[0:8])
            if l < len(self.data):
                return
            msg_count += 1
            global greetings
            req = example_pb2.DummyReq()
            req.greetings = greetings[int(random.uniform(0, len(greetings)))]
            self.send(2, req)
            if len(self.data) >= l:
                self.data = self.data[l:-1]
            else:
                return
        
    def send(self, msg_id, msg):
        data = msg.SerializeToString()
        s = struct.pack('!2I', len(data) + 8, msg_id)
        self.transport.write(s+data)
        
class RobotClientFactory(ClientFactory):   
    def buildProtocol(self, addr):
        return RobotProtocol()
   
    def clientConnectionLost(self, connector, reason):
        reactor.connectTCP('127.0.0.1', 12345, RobotClientFactory())
    
    def clientConnectionFailed(self, connector, reason):
        print 'Connection failed. Reason:', reason

def print_count():
    global msg_count
    print "message count:" + str(msg_count)

if __name__ == '__main__':
    global msg_count
    global greetings
    greetings = []
    if len(greetings) == 0:
        for i in range(0, 64):
            greetings.append(generate_random_str())
    msg_count = 0
    for i in range(0, 500):
        reactor.connectTCP('127.0.0.1', 12345, RobotClientFactory())
    timer = task.LoopingCall(print_count)
    timer.start(2.0, now=False)
    reactor.run()